<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="备份列表" name="list">
        <el-row :gutter="10" class="mb-8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleCreateBackup">创建备份</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Refresh" :disabled="single" @click="handleRestore">还原数据</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Download" :disabled="single" @click="handleDownload">下载</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="backupList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="任务ID" align="center" prop="taskId" width="80" />
          <el-table-column label="备份名称" align="center" prop="taskName" :show-overflow-tooltip="true" />
          <el-table-column label="备份类型" align="center" prop="backupType">
            <template #default="scope">
              <el-tag :type="scope.row.backupType === 'full' ? 'primary' : 'success'">
                {{ scope.row.backupType === 'full' ? '全量备份' : '增量备份' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="文件名称" align="center" prop="fileName" :show-overflow-tooltip="true" />
          <el-table-column label="文件大小" align="center" prop="fileSize" width="100" />
          <el-table-column label="状态" align="center" prop="status" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusLabel(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="开始时间" align="center" prop="startTime" width="160" />
          <el-table-column label="完成时间" align="center" prop="endTime" width="160" />
          <el-table-column label="耗时" align="center" prop="duration" width="100" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
            <template #default="scope">
              <el-button v-if="scope.row.status === 'success'" type="text" icon="Refresh" @click="handleRestore(scope.row)">还原</el-button>
              <el-button v-if="scope.row.status === 'success'" type="text" icon="Download" @click="handleDownload(scope.row)">下载</el-button>
              <el-button type="text" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-tab-pane>
      
      <el-tab-pane label="备份设置" name="config">
        <el-form ref="configForm" :model="configForm" :rules="configRules" label-width="120px">
          <el-form-item label="自动备份" prop="autoBackup">
            <el-switch v-model="configForm.autoBackup" />
          </el-form-item>
          
          <el-form-item v-if="configForm.autoBackup" label="备份时间" prop="backupTime">
            <el-time-picker v-model="backupTime" format="HH:mm" placeholder="选择备份时间" />
          </el-form-item>
          
          <el-form-item v-if="configForm.autoBackup" label="备份周期" prop="backupCycle">
            <el-select v-model="configForm.backupCycle" placeholder="请选择备份周期">
              <el-option label="每天" value="daily" />
              <el-option label="每周" value="weekly" />
              <el-option label="每月" value="monthly" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="保留天数" prop="keepDays">
            <el-input-number v-model="configForm.keepDays" :min="1" :max="365" />
          </el-form-item>
          
          <el-form-item label="备份路径" prop="backupPath">
            <el-input v-model="configForm.backupPath" placeholder="请输入备份文件存储路径" />
          </el-form-item>
          
          <el-form-item label="压缩级别" prop="compressionLevel">
            <el-select v-model="configForm.compressionLevel" placeholder="请选择压缩级别">
              <el-option label="低" value="low" />
              <el-option label="中" value="medium" />
              <el-option label="高" value="high" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="saveConfig">保存配置</el-button>
            <el-button @click="resetConfig">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <!-- 创建备份对话框 -->
    <el-dialog title="创建备份" v-model="createBackupDialogVisible" width="500px" append-to-body>
      <el-form ref="createBackupForm" :model="createBackupForm" :rules="createBackupRules" label-width="100px">
        <el-form-item label="备份名称" prop="taskName">
          <el-input v-model="createBackupForm.taskName" placeholder="请输入备份名称" />
        </el-form-item>
        <el-form-item label="备份类型" prop="backupType">
          <el-radio-group v-model="createBackupForm.backupType">
            <el-radio label="full">全量备份</el-radio>
            <el-radio label="incremental">增量备份</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="createBackupForm.remark" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCreateBackup">确 定</el-button>
          <el-button @click="cancelCreateBackup">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 还原确认对话框 -->
    <el-dialog title="还原确认" v-model="restoreDialogVisible" width="400px" append-to-body>
      <div class="restore-warning">
        <el-alert
          title="警告：数据还原将覆盖当前系统数据，请确保已做好相关数据备份"
          type="warning"
          :closable="false"
          show-icon
        />
      </div>
      <div class="restore-info" v-if="selectedBackup">
        <p><strong>备份名称：</strong>{{ selectedBackup.taskName }}</p>
        <p><strong>备份时间：</strong>{{ selectedBackup.startTime }}</p>
        <p><strong>文件大小：</strong>{{ selectedBackup.fileSize }}</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="confirmRestore">确认还原</el-button>
          <el-button @click="restoreDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBackupList, createBackupTask, restoreData, downloadBackup, deleteBackup, getBackupConfig, updateBackupConfig } from '@/api/system/backup'

// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 遮罩层
const loading = ref(false)
// 总条数
const total = ref(0)
// 备份列表数据
const backupList = ref([])
// 当前激活的标签页
const activeTab = ref('list')
// 创建备份对话框
const createBackupDialogVisible = ref(false)
// 还原确认对话框
const restoreDialogVisible = ref(false)
// 选中的备份数据
const selectedBackup = ref(null)
// 备份时间
const backupTime = ref(new Date(2000, 0, 1, 2, 0))

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  status: ''
})

// 备份配置表单
const configForm = reactive({
  autoBackup: false,
  backupTime: '02:00',
  backupCycle: 'daily',
  keepDays: 30,
  backupPath: '/data/backup',
  compressionLevel: 'medium'
})

// 备份配置表单规则
const configRules = {
  keepDays: [{ required: true, message: '请输入保留天数', trigger: 'blur' }],
  backupPath: [{ required: true, message: '请输入备份路径', trigger: 'blur' }]
}

// 创建备份表单
const createBackupForm = reactive({
  taskName: '',
  backupType: 'full',
  remark: ''
})

// 创建备份表单规则
const createBackupRules = {
  taskName: [{ required: true, message: '请输入备份名称', trigger: 'blur' }],
  backupType: [{ required: true, message: '请选择备份类型', trigger: 'change' }]
}

// 获取备份状态类型
function getStatusType(status) {
  switch (status) {
    case 'success': return 'success'
    case 'fail': return 'danger'
    case 'running': return 'primary'
    default: return 'info'
  }
}

// 获取备份状态标签
function getStatusLabel(status) {
  switch (status) {
    case 'success': return '成功'
    case 'fail': return '失败'
    case 'running': return '运行中'
    default: return '未知'
  }
}

/** 查询备份列表 */
function getList() {
  loading.value = true
  getBackupList(queryParams).then(response => {
    backupList.value = response.data.list
    total.value = response.data.total
    loading.value = false
  })
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.taskId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 创建备份按钮操作 */
function handleCreateBackup() {
  createBackupForm.taskName = `手动备份_${new Date().toISOString().split('T')[0].replace(/-/g, '')}`
  createBackupForm.backupType = 'full'
  createBackupForm.remark = ''
  createBackupDialogVisible.value = true
}

/** 提交创建备份 */
function submitCreateBackup() {
  // TODO: 表单验证
  createBackupTask(createBackupForm).then(response => {
    ElMessage.success('备份任务已创建，请稍后查看结果')
    createBackupDialogVisible.value = false
    getList()
  })
}

/** 取消创建备份 */
function cancelCreateBackup() {
  createBackupDialogVisible.value = false
}

/** 还原按钮操作 */
function handleRestore(row) {
  const taskId = row?.taskId || ids.value[0]
  selectedBackup.value = row || backupList.value.find(item => item.taskId === taskId)
  restoreDialogVisible.value = true
}

/** 确认还原数据 */
function confirmRestore() {
  const taskId = selectedBackup.value.taskId
  restoreData(taskId).then(response => {
    ElMessage.success('数据还原任务已启动，请稍后查看结果')
    restoreDialogVisible.value = false
  })
}

/** 下载按钮操作 */
function handleDownload(row) {
  const taskId = row?.taskId || ids.value[0]
  downloadBackup(taskId)
}

/** 删除按钮操作 */
function handleDelete(row) {
  const taskIds = row?.taskId || ids.value.join(',')
  ElMessageBox.confirm('是否确认删除备份任务编号为"' + taskIds + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteBackup(taskIds).then(() => {
      getList()
      ElMessage.success('删除成功')
    })
  })
}

/** 加载备份配置 */
function loadBackupConfig() {
  getBackupConfig().then(response => {
    Object.assign(configForm, response.data)
    
    // 处理时间
    if (configForm.backupTime) {
      const [hours, minutes] = configForm.backupTime.split(':').map(Number)
      backupTime.value = new Date(2000, 0, 1, hours, minutes)
    }
  })
}

/** 保存备份配置 */
function saveConfig() {
  // 处理时间格式
  const hours = backupTime.value.getHours().toString().padStart(2, '0')
  const minutes = backupTime.value.getMinutes().toString().padStart(2, '0')
  configForm.backupTime = `${hours}:${minutes}`
  
  updateBackupConfig(configForm).then(() => {
    ElMessage.success('备份配置已更新')
  })
}

/** 重置备份配置 */
function resetConfig() {
  loadBackupConfig()
}

onMounted(() => {
  getList()
  loadBackupConfig()
})
</script>

<style scoped>
.restore-warning {
  margin-bottom: 20px;
}
.restore-info {
  margin-top: 20px;
  line-height: 1.8;
}
</style> 